package cn.codergege.demo.dao.jpa;

import cn.codergege.demo.domain.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import cn.codergege.demo.dao.DepartmentRepository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
@Transactional
public class DepartmentRepositoryJpa implements DepartmentRepository {

    @PersistenceContext
    private EntityManager em;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void add(Department department) {
        em.persist(department);
    }

    @Override
    public List<Department> findAll() {
        // todo: 用 jpa 实现
        String sql = "select id, name from t_department";
        List<Department> depts = jdbcTemplate.query(sql, new RowMapper<Department>() {
            @Override
            public Department mapRow(ResultSet rs, int rowNum) throws SQLException {
                Department dept = new Department();
                dept.setId(rs.getInt(1));
                dept.setName(rs.getString(2));
                return dept;
            }
        });
        return depts;
    }

    @Override
    public Department getDepartmentById(Integer id) {
        return em.find(Department.class, id);
    }

}
